package com.demo.juc.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

public class CASDemo02 {
    //比较并交换
    public static void main(String[] args) {
        //AtomicInteger atomicInteger = new AtomicInteger(2020);//原子类
        //Integer 使用了对象缓存机制，默认范围是 -128 ~ 127 ，推荐使用静态工厂方法 valueOf 获取对象实例，而不是 new，因为 valueOf 使用缓存，而 new 一定会创建新的对象分配新的内存空间；
        AtomicStampedReference<Integer> atomicInteger = new AtomicStampedReference<>(11,1);//初始值，版本号时间戳
        new Thread(()->{
            int stamp = atomicInteger.getStamp();//获得版本号
            System.out.println("A = >" + stamp);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //最后两个参数，拿到最新的版本号，把版本号+1
            System.out.println("a:"+atomicInteger.compareAndSet(11, 22, atomicInteger.getStamp(), atomicInteger.getStamp() + 1));
            System.out.println("A2 = >"+atomicInteger.getStamp());
            //把这个值该回去
            System.out.println(atomicInteger.compareAndSet(22, 11, atomicInteger.getStamp(), atomicInteger.getStamp() + 1));
            System.out.println("A3 = >"+atomicInteger.getStamp());

        },"a").start();


        new Thread(()->{
            int stamp = atomicInteger.getStamp();//获得版本号
            System.out.println("B = >" + stamp);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("b:"+atomicInteger.compareAndSet(11, 66, stamp, stamp + 1));

            System.out.println("b2 = >"  +atomicInteger.getStamp());
        },"b").start();

    }
}
